package com.studyweb.mapper;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

public class JsonTypeHandler extends BaseTypeHandler<Map<Long, Object>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<Long, Object> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            ps.setString(i, JSON.toJSONString(parameter));
        } else {
            ps.setString(i, null);
        }
    }

    @Override
    public Map<Long, Object> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        if (json != null && !json.isEmpty()) {
            try {
                return JSON.parseObject(json, new TypeReference<Map<Long, Object>>() {});
            } catch (Exception e) {
                // 如果解析失败，返回null
                return null;
            }
        }
        return null;
    }

    @Override
    public Map<Long, Object> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        if (json != null && !json.isEmpty()) {
            try {
                return JSON.parseObject(json, new TypeReference<Map<Long, Object>>() {});
            } catch (Exception e) {
                // 如果解析失败，返回null
                return null;
            }
        }
        return null;
    }

    @Override
    public Map<Long, Object> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        if (json != null && !json.isEmpty()) {
            try {
                return JSON.parseObject(json, new TypeReference<Map<Long, Object>>() {});
            } catch (Exception e) {
                // 如果解析失败，返回null
                return null;
            }
        }
        return null;
    }
}